package cn.tedu.account.tcc;

import cn.tedu.account.entity.Account;
import cn.tedu.account.mapper.AccountMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @description:
 * @author: LiuXingYu
 * @date: 2021/9/24 10:38
 */
@Component
public class AccountTccActionImpl implements AccountTccAction {

    @Autowired
    private AccountMapper accountMapper;

    @Transactional
    @Override
    public boolean prepare(BusinessActionContext businessActionContext, Long userId, BigDecimal money) {
        Account account = accountMapper.selectByUserId(userId);
        if (account.getResidue().compareTo(money) < 0) {
            throw new RuntimeException("可用金额不足");
        }
        accountMapper.updateResidueToFrozen(userId, money);
        ResultHolder.setResult(AccountTccAction.class, businessActionContext.getXid(), "p");
        return true;
    }

    @Transactional
    @Override
    public synchronized boolean commit(BusinessActionContext businessActionContext) {
        if (ResultHolder.getResult(AccountTccAction.class, businessActionContext.getXid()) == null) {
            return true;
        }
        Long userId = Long.valueOf(businessActionContext.getActionContext("userId").toString());
        BigDecimal money = new BigDecimal(businessActionContext.getActionContext("money").toString());
        accountMapper.updateFrozenToUsed(userId, money);
        ResultHolder.removeResult(AccountTccAction.class, businessActionContext.getXid());
        return true;
    }

    @Transactional
    @Override
    public synchronized boolean rollback(BusinessActionContext businessActionContext) {
        if (ResultHolder.getResult(AccountTccAction.class, businessActionContext.getXid()) == null) {
            return true;
        }
        Long userId = Long.valueOf(businessActionContext.getActionContext("userId").toString());
        BigDecimal money = new BigDecimal(businessActionContext.getActionContext("money").toString());
        accountMapper.updateFrozenToResidue(userId, money);
        ResultHolder.removeResult(AccountTccAction.class, businessActionContext.getXid());
        return true;
    }
}
